import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class PracticeBody extends StatefulWidget {
  final Function(int) generateQuestions; // 修改为接受题目数量的函数
  final VoidCallback submitAnswers;
  final List<Map<String, dynamic>> questions; // 修改为包含题目信息的列表
  final List<String> userAnswers;
  final int totalQuestions;
  final int correctCount;
  final int incorrectCount;
  final int score; // 添加得分参数
  final Function(int, String) updateAnswer; // 新增回调函数
  final List<TextEditingController> controllers;
  final Function(int) updateCorrectCount;
  final Function(int) updateIncorrectCount;
  final Function(int) updateScore;

  const PracticeBody({
    super.key,
    required this.generateQuestions,
    required this.submitAnswers,
    required this.questions,
    required this.userAnswers,
    required this.totalQuestions,
    required this.correctCount,
    required this.incorrectCount,
    required this.score, // 初始化得分参数
    required this.updateAnswer, // 初始化回调函数
    required this.controllers,
    required this.updateCorrectCount, // 添加回调
    required this.updateIncorrectCount, // 添加回调
    required this.updateScore, // 添加回调
  });

  @override
  State<PracticeBody> createState() => _PracticeBodyState();
}

class _PracticeBodyState extends State<PracticeBody> {
  int selectedQuestionCount = 1; // 默认选择生成1题
  late int totalTime; // 总答题时间（秒）
  late int remainingTime; // 剩余时间（秒）
  late int totalScore;  // 满分
  Timer? countdownTimer; // 倒计时计时器
  String evaluation = ''; // 评价
  String suggestion = ''; // 建议
  bool isSubmitted = false; // 标记是否已提交答案
  List<Map<String, dynamic>> submissionResults = []; // 存储题目结果

  @override
  void initState() {
    super.initState();
    // 确保在这里初始化所有变量
    totalTime = selectedQuestionCount * 15;
    remainingTime = totalTime; // 初始化剩余时间
    _updateTotalScore();
    submissionResults = []; // 初始化为空列表
  }


  void _updateTotalScore() {
    totalScore = selectedQuestionCount * 2;
  }

  // 检查是否有未作答的题目
  bool _hasUnansweredQuestions() {
    return widget.userAnswers.any((answer) => answer.isEmpty);
  }

  // 显示确认对话框
  Future<void> _showConfirmationDialog() async {
    await showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("确认提交"),
          content: const Text(
            "你还有未作答的题目，是否确认提交答案？",
            style: TextStyle(fontSize: 16),
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(); // 关闭对话框
              },
              child: const Text("取消"),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop(); // 关闭对话框
                countdownTimer?.cancel(); // 如果已经有倒计时，先取消它
                _submitAndMarkAsSubmitted(); // 确认提交
              },
              child: const Text("确认"),
            ),
          ],
        );
      },
    );
  }

  Future<void> _showAlreadySubmittedDialog() async {
    await showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("重复提交"),
          content: const Text("答案已提交，请勿重复提交", style: TextStyle(fontSize: 16),),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(); // 关闭对话框
              },
              child: const Text("确认"),
            ),
          ],
        );
      },
    );
  }

  void _updateEvaluationAndSuggestion() {
    String accuracy = widget.totalQuestions > 0
        ? (widget.correctCount / widget.totalQuestions * 100).toStringAsFixed(1)
        : "0.0";

    // 根据正确率设置评价和建议
    double accuracyValue = double.parse(accuracy);
    if (accuracyValue == 100.0) {
      evaluation = "超级优秀";
      suggestion = "不要骄傲";
    } else if (accuracyValue > 90.0) {
      evaluation = "优秀";
      suggestion = "继续保持";
    } else if (accuracyValue > 80.0) {
      evaluation = "较好";
      suggestion = "继续加油";
    } else if (accuracyValue > 70.0) {
      evaluation = "良好";
      suggestion = "不要放弃";
    } else if (accuracyValue > 60.0) {
      evaluation = "及格";
      suggestion = "别灰心啊";
    } else if (accuracyValue > 40.0) {
      evaluation = "不及格";
      suggestion = "别贪玩了";
    } else {
      evaluation = "特差";
      suggestion = "菜就多练";
    }
  }

  @override
  void dispose() {
    countdownTimer?.cancel(); // 界面销毁时取消倒计时
    super.dispose();
  }

  // 开始倒计时
  void _startTimer() {
    countdownTimer?.cancel(); // 如果已经有倒计时，先取消它
    countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (remainingTime > 0) {
        setState(() {
          remainingTime--;
        });
      } else {
        timer.cancel(); // 倒计时结束
        // 时间结束时自动提交答案
        _submitAndMarkAsSubmitted();
      }
    });
  }

  // 格式化时间为 "mm:ss"
  String _formatTime(int seconds) {
    final minutes = (seconds ~/ 60).toString().padLeft(2, '0');
    final secs = (seconds % 60).toString().padLeft(2, '0');
    return '$minutes:$secs';
  }

  // 提交答案并封装 JSON 数据
  void _submitAndMarkAsSubmitted() async {
    setState(() {
      isSubmitted = true;   // 标记已提交
    });
    // widget.submitAnswers(); // 调用父组件提交逻辑

    // 封装 JSON 数据
    final List<Map<String, dynamic>> requestData = [];
    for (int i = 0; i < widget.questions.length; i++) {
      requestData.add({
        "examinationId": widget.questions[i]["examinationId"],
        "expressId": widget.questions[i]["expressId"],
        "ans": widget.controllers[i].text.trim(),
      });
    }

    // 提交到服务器
    const String apiUrl = "http://101.34.58.190:8080/submit";
    try {
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {"Content-Type": "application/json"},
        body: jsonEncode(requestData),
      );

      if (response.statusCode == 200) {
        // 成功处理返回的数据
        final responseData = jsonDecode(response.body);

        setState(() {
          // 更新 submissionResults 为返回的题目结果
          submissionResults = List<Map<String, dynamic>>.from(responseData["problems"]);
          // 更新计数和得分
          widget.updateCorrectCount(responseData["correctCount"]);
          widget.updateIncorrectCount(responseData["wrongCount"]);
          widget.updateScore(responseData["totalScore"]);
        });

        // 成功处理
        print("提交成功：${response.body}");
      } else {
        // 失败处理
        print("提交失败：${response.statusCode}, ${response.body}");
      }
    } catch (e) {
      print("请求失败：$e");
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text("提交失败，请检查网络连接！")),
      );
    }

    countdownTimer?.cancel(); // 如果已经有倒计时，先取消它
  }



  @override
  Widget build(BuildContext context) {
    // 计算正确率
    String accuracy = widget.totalQuestions > 0
        ? (widget.correctCount / widget.totalQuestions * 100).toStringAsFixed(1)
        : "0.0";

    // 计算正确率并更新评价和建议
    _updateEvaluationAndSuggestion();

    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.blue.shade50, Colors.blue.shade100],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
      ),
      child: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 显示倒计时
              Text(
                '答题时间：${_formatTime(remainingTime)}',
                style: const TextStyle(
                  fontSize: 25,
                  fontWeight: FontWeight.bold,
                  color: Colors.red,
                ),
              ),
              const SizedBox(height: 16),

              // 滑动条选择题目数量
              const Text(
                '选择生成题目数量:',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              SliderTheme(
                data: SliderThemeData(
                  activeTrackColor: Colors.blue.shade700,
                  inactiveTrackColor: Colors.blue.shade200,
                  thumbColor: Colors.blue.shade400,
                  overlayColor: Colors.blue.withAlpha(32),
                  valueIndicatorColor: Colors.blue.shade300,
                ),
                child: Slider(
                  value: selectedQuestionCount.toDouble(),
                  min: 1,
                  max: 100,
                  divisions: 100,
                  label: '$selectedQuestionCount',
                  onChanged: (double value) {
                    setState(() {
                      selectedQuestionCount = value.toInt();
                      totalTime = selectedQuestionCount * 15; // 更新总时间
                      remainingTime = totalTime; // 重置倒计时
                      _updateTotalScore(); // 更新满分
                      countdownTimer?.cancel(); // 重启倒计时
                      // _startTimer();
                    });
                  },
                ),
              ),
              Text(
                '题目数量: $selectedQuestionCount',
                style: const TextStyle(fontSize: 16),
              ),

              const SizedBox(height: 16),

              // 生成题目按钮
              Center(
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue.shade500,
                    padding: const EdgeInsets.symmetric(
                        vertical: 12, horizontal: 22),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                  onPressed: () {
                    setState(() {
                      // 重置用户答案为空字符串列表，长度与题目数量一致
                      widget.userAnswers.clear();
                      widget.userAnswers.addAll(List.filled(selectedQuestionCount, ''));

                      // 更新总时间和剩余时间
                      totalTime = selectedQuestionCount * 15;
                      remainingTime = totalTime;

                      // 启动倒计时
                      _startTimer();
                    });
                    // 调用父组件的生成题目方法
                    widget.generateQuestions(selectedQuestionCount);
                    isSubmitted = false;
                  },
                  child: const Text(
                    '随机生成',
                    style: TextStyle(fontSize: 16, color: Colors.white),
                  ),
                ),
              ),

              const SizedBox(height: 16),
              const Divider(thickness: 2, color: Colors.blueAccent),

              // 题目列表
              ListView.builder(
                shrinkWrap: true, // 避免无限高度错误
                physics: const NeverScrollableScrollPhysics(), // 禁用内层滚动
                itemCount: widget.questions.length,
                itemBuilder: (context, index) {
                  final question = widget.questions[index];
                  // 在 submissionResults 中查找对应题目
                  final submissionResult = submissionResults.firstWhere(
                        (result) => result["expressId"] == question["expressId"],
                    orElse: () => {"isRight": null},
                  );
                  final isRight = submissionResult["isRight"];

                  final backgroundColor = isRight == true
                      ? Colors.green.shade300
                      : isRight == false
                      ? Colors.red.shade300
                      : Colors.white;

                  return Card(
                    margin:
                    const EdgeInsets.symmetric(vertical: 8, horizontal: 4),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                    elevation: 2,
                    color: backgroundColor, // 动态背景颜色
                    child: Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text(
                              '${index + 1}： ${widget.questions[index]["express"]} ',
                              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                            ),
                          ),
                          SizedBox(
                            width: 80,
                            child: TextField(
                              controller: widget.controllers[index], // 使用正确类型的 Controller
                              keyboardType: TextInputType.number,
                              decoration: InputDecoration(
                                border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(8),
                                ),
                              ),
                              onChanged: (value) {
                                widget.updateAnswer(index, value); // 更新对应答案
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),

              const Divider(thickness: 2, color: Colors.blueAccent),

              // 提交答案按钮
              Center(
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.green.shade400,
                    padding: const EdgeInsets.symmetric(
                        vertical: 12, horizontal: 32),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                  onPressed: () {
                    if (isSubmitted) {
                      _showAlreadySubmittedDialog(); // 显示重复提交提示
                    } else {
                      if (_hasUnansweredQuestions()) {
                        _showConfirmationDialog(); // 显示确认对话框
                      } else {
                        _submitAndMarkAsSubmitted(); // 没有未作答，直接提交
                      }
                    }
                  },
                  child: const Text(
                    '提交答案',
                    style: TextStyle(fontSize: 16, color: Colors.white),
                  ),
                ),
              ),

              const SizedBox(height: 16),

              // 显示结果
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.blue.shade50,
                      borderRadius: BorderRadius.circular(10),
                      border: Border.all(color: Colors.blue.shade200),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '总题数: $selectedQuestionCount',
                          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold,),
                        ),
                        Text(
                          '正确题目数: ${widget.correctCount}',
                          style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Colors.green),
                        ),
                        Text(
                          '错误题目数: ${widget.incorrectCount}',
                          style:
                          const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Colors.red),
                        ),
                        Text(
                          '正确率: $accuracy%',
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Colors.blue,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.blue.shade50,
                      borderRadius: BorderRadius.circular(10),
                      border: Border.all(color: Colors.blue.shade200),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '题目总分: $totalScore',
                          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold,),
                        ),
                        Text(
                          '你的得分: ${widget.score}',
                          style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Colors.green),
                        ),
                        Text(
                          '评价: $evaluation',
                          style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Colors.orange),
                        ),
                        Text(
                          '建议: $suggestion',
                          style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Colors.brown),
                        )
                      ],
                    ),
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}